import './config';
const axios = require('axios')
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
//添加灰度标记，用于微服务调试
let grayMark = API_CONFIG.grayMark;
if(grayMark) {
    axios.defaults.headers.common['gray-mark'] = grayMark;
}
var loginConfirm = 0;

/**
 * 跳转至登录页
 */
function jumpToLoginPage(){
    location=envConfig[env].loginPath;
}

/**
 * 登录超时提示。添加限制以防重复提示
 * @param vue
 * @param response
 * @param hook
 */
function showLoginTip(vue,response,hook) {

    if(loginConfirm<0) {
        loginConfirm = 0;
    }
    if(loginConfirm>0) {
        if(hook) {
            hook(response.data);
        }
        return;
    }

    loginConfirm++;

    vue.$confirm('当前会话已超时，请重新登录', '提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        loginConfirm--;
        jumpToLoginPage();
    }).catch(() => {
        if (hook) {
            hook(response.data);
        }
        loginConfirm--;
    });
}

Vue.prototype.$post = function (url, param, success, hook) {
    let extraParam = {};
    extraParam.headers = {'Referer-Nuoda':location.href};
    if(this.$store&&this.$store.state.token) {
        extraParam.headers.token = this.$store.state.token;
    }
    axios.post(this.$ctx + url, param , extraParam).then((response) => {
        if (response.data.code == 403) {
            showLoginTip(this,response,hook);
            if (hook) {
                hook(response.data);
            }
            return;
        }
        if (response.data.code != 0) {
            this.$message.warning(response.data.msg);
            if (hook) {
                hook(response.data);
            }
            return;
        }
        if (success) {
            success(response.data);
        }
        if (hook) {
            hook(response.data);
        }

    }).catch(e => {
        // if(fail){
        //   fail(e);
        // } else {
        console.error(e);
        this.$message.error("请求异常");
        // }
        if (hook) {
            hook({code:-1,msg:'前端脚本执行异常',data:e});
        }
    });

}
//前端缓存路径，这些数据基本不会变动
Vue.prototype.$ajaxCachePaths = [
    '/company/data',
    '/meta/dataType',
    '/meta/unitType',
    '/field/type',
];
//前端缓存数据
Vue.prototype.$ajaxCacheData = {};

//添加缓存路径
Vue.prototype.addAjaxCachePath = function(path){
    for(let item of this.$ajaxCachePaths) {
        if(item == path) {
            return;
        }
    }
    this.$ajaxCachePaths.push(path);
}

Vue.prototype.$get = function (url, param, success, hook) {
    let needCache = false;
    if(!param||Object.keys(param).length==0) {
        for (let path of this.$ajaxCachePaths) {
            //优先使用缓存，减少请求数量
            if (path == url && this.$ajaxCacheData[path] && this.$ajaxCacheData[path].code == 0) {
                if (success) {
                    success(this.$ajaxCacheData[path]);
                }
                if (hook) {
                    hook(this.$ajaxCacheData[path]);
                }
                return;
            } else if (path == url) {
                needCache = true;
                break;
            }
        }
    }
    //请求参数添加时间戳，解决ie浏览器缓存数据问题
    let timestamp = new Date().getTime();
    if(!param) {
        param = {};
    }
    param.t = timestamp;
    let headers = {'Referer-Nuoda':location.href};
    if(this.$store&&this.$store.state.token) {
        headers.token = this.$store.state.token;
    }
    axios.get(this.$ctx + url, {params: param,headers:headers}).then((response) => {
        if (response.data.code == 403) {
            if(url == '/user/info/current_user') {
                //如果是获取当前用户信息，则认为是未登录直接跳转主页面
                jumpToLoginPage();
                return;
            }
            showLoginTip(this,response,hook);
            if (hook) {
                hook(response.data);
            }
            return;
        }
        if (response.data.code != 0) {
            this.$message.warning(response.data.msg);
            if (hook) {
                hook(response.data);
            }
            return;
        }
        if(needCache) {
            this.$ajaxCacheData[url] = response.data;
        }
        if (success) {
            success(response.data);
        }
        if (hook) {
            hook(response.data);
        }

    }).catch(e => {
        console.error(e);
        this.$message.error("请求异常");
        // }
        if (hook) {
            hook({code:-1,msg:'前端脚本执行异常',data:e});
        }
    });

}

Vue.prototype.$getHttpPromise = async function (url, param ) {
    try {
        let res = await axios.get(this.$ctx + url, {params: param});
        if (res.data.code == 403) {
            if(url == '/user/info/current_user') {
                //如果是获取当前用户信息，则认为是未登录直接跳转主页面
                jumpToLoginPage();
                return;
            }
            showLoginTip(this,res,null);
            return;
        }
        if (res.data.code != 0) {
            this.$message.warning(res.data.msg);
            return;
        }
        res = res.data
        return new Promise((resolve) => {
            resolve(res)
        })
    } catch (err) {
        alert('服务器出错')
        console.log(err)
    }
}

//自定义权限检查
Vue.prototype.checkPermission = function (permissions) {
    if (!permissions) {
        return true;
    }
    let perList = this.$store.state.user.permissionList;


    let permissionArr = permissions.split(',');
    let hasPermissionCount = 0;
    let permissionCount = permissionArr.length;
    for (let item of permissionArr) {
        if (item == '') {
            continue;
        }
        for (let p of perList) {
            if (item == p.id) {
                hasPermissionCount++;
                break;
            }
        }

    }

    // console.log('check:'+permissions+'  requrie:'+permissionCount+',has:'+hasPermissionCount)
    return hasPermissionCount >= permissionCount;
}
//自定义权限检查
Vue.prototype.hasAnyPermission = function (permissions) {
    if (!permissions) {
        return true;
    }
    let perList = this.$store.state.user.permissionList;

    for (let item of permissions) {
        if (item == '') {
            continue;
        }
        for (let p of perList) {
            if (item == p.id) {
                return true;
            }
        }

    }

    return false;
}
//检查用户是否拥有特定角色
Vue.prototype.hasRole = function (roleId) {
    if (!roleId) {
        return true;
    }
    let roleList = this.$store.state.user.roleList;

    for (let item of roleList) {
        if (item.code == roleId) {
            return true;
        }
    }
    return false;
}
